package com.borqsprocessmanager.db;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class SampleContextprovider extends ContentProvider {

    private static final UriMatcher mUriMatcher;
    private static final int SAMPLE = 1;
    private static final int SAMPLE_ID = 2;

    private static HashMap<String, String> sampleMap;

    private DBHelper mOpenHelper;

    @Override
    public boolean onCreate() {
        mOpenHelper = DBHelper.getInstance(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        String orderBy;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理

        case SAMPLE_ID:
            qb.appendWhere(DBProvider.SamplesTable._ID + "=?");
            selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
                    new String[] { uri.getLastPathSegment() });
        case SAMPLE:
            qb.setTables(DBProvider.SamplesTable.TABLE_NAME);
            qb.setProjectionMap(sampleMap);
            if (TextUtils.isEmpty(sortOrder)) {
                orderBy = DBProvider.SamplesTable.DEFAULT_SORT_ORDER;
            } else {
                orderBy = sortOrder;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
                null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public String getType(Uri uri) {
        switch (mUriMatcher.match(uri)) {
        case SAMPLE:
            return DBProvider.CONTENT_TYPE;
        case SAMPLE_ID:
            return DBProvider.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        ContentValues contentValues = null;
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String tableName = "";
        long rowId = 0;
        // String nullColumn = "";

        if (null != values) {
            contentValues = values;
        } else {
            contentValues = new ContentValues();
        }

        switch (mUriMatcher.match(uri)) {
        case SAMPLE:
            tableName = DBProvider.SamplesTable.TABLE_NAME;
            Cursor c = queryProcessPkg(db, tableName, contentValues);
            if (c.getCount() == 0) {
                rowId = db.insert(tableName, null, contentValues);

            } else {
                String selecation = DBProvider.SamplesTable._ID + "=?";
                String[] selectionArgs = new String[] { contentValues
                        .getAsString(DBProvider.SamplesTable._ID) };
                rowId = db.update(DBProvider.SamplesTable.TABLE_NAME, values,
                        selecation, selectionArgs);
            }
        default:
            break;
        }
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(uri, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    private Cursor queryProcessPkg(SQLiteDatabase db, String tableName,
            ContentValues contentValues) {
        String[] columns = new String[] { DBProvider.SamplesTable._ID };
        String selecation = DBProvider.SamplesTable._ID + "=?";
        String[] selectionArgs = new String[] { contentValues
                .getAsString(DBProvider.SamplesTable._ID) };
        Cursor c = db.query(tableName, columns, selecation, selectionArgs,
                null, null, null, null);
        return c;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String finalWhere;
        int count;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理，注意下面用到的表名不要弄错了
        case SAMPLE:
            count = db.delete(DBProvider.SamplesTable.TABLE_NAME, selection,
                    selectionArgs);
            break;
        case SAMPLE_ID:
            finalWhere = DatabaseUtils.concatenateWhere(
                    DBProvider.SamplesTable._ID + " = "
                            + ContentUris.parseId(uri), selection);
            count = db.delete(DBProvider.SamplesTable.TABLE_NAME, finalWhere,
                    selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        String finalWhere;

        switch (mUriMatcher.match(uri)) {
        case SAMPLE_ID:
            // If URI is for a particular row ID, update is based on
            // incoming
            // data but modified to restrict to the given ID.
            selection = DatabaseUtils.concatenateWhere(
                    DBProvider.SamplesTable._ID + " = "
                            + ContentUris.parseId(uri), selection);
        case SAMPLE:
            // If URI is main table, update uses incoming where clause and
            // args.
            count = db.update(DBProvider.SamplesTable.TABLE_NAME, values,
                    selection, selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    static {
        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        mUriMatcher.addURI(DBProvider.SamplesTable.AUTHORITY,
                DBProvider.SamplesTable.TABLE_NAME, SAMPLE);
        mUriMatcher.addURI(DBProvider.SamplesTable.AUTHORITY,
                DBProvider.SamplesTable.TABLE_NAME + "/#", SAMPLE_ID);

        sampleMap = new HashMap<String, String>();
        sampleMap.put(DBProvider.SamplesTable._ID, DBProvider.SamplesTable._ID);
        sampleMap.put(DBProvider.SamplesTable.START_TIME,
                DBProvider.SamplesTable.START_TIME);
        sampleMap.put(DBProvider.SamplesTable.END_TIME,
                DBProvider.SamplesTable.END_TIME);
        sampleMap.put(DBProvider.SamplesTable.START_LEVEL,
                DBProvider.SamplesTable.START_LEVEL);
        sampleMap.put(DBProvider.SamplesTable.END_LEVEL,
                DBProvider.SamplesTable.END_LEVEL);

    }

}
